<template>
  <div class="app-container">
    <el-card class="box-card">
      <h3>{{$t('用户详情')}}</h3>
      <el-form ref="dataForm" :rules="rules" :model="admin" label-width="150px">
        <el-form-item :label="$t('Partner_name')" prop="nickName">
          <el-input v-model="admin.nickName" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
        </el-form-item>

        <el-form-item :label="$t('员工代号')" prop="code">
          <el-input v-model="admin.code" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
        </el-form-item>
        <el-form-item :label="$t('员工账号')" prop="username">
          <el-input v-model="admin.username" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
        </el-form-item>
        <el-form-item :label="$t('社保号码')" prop="socialSecurityNumber">
          <el-input v-model="admin.socialSecurityNumber"/>
        </el-form-item>
        <el-form-item :label="$t('性别')" prop="gender">
          <el-select v-model="admin.gender" clearable :placeholder="$t('请选择')">
            <el-option :value="1" :label="$t('其他')"></el-option>
            <el-option :value="2" :label="$t('女')"></el-option>
            <el-option :value="3" :label="$t('男')"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('生日')" prop="birthday">
          <el-date-picker clearable
                          class="filter-date-item"
                          v-model="admin.birthday"
                          type="date"
                          value-format="yyyy-MM-dd" :placeholder="$t('请选择')">
          </el-date-picker>
        </el-form-item>

        <el-form-item :label="$t('Partner_picture')" prop="avatar">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadAvatar"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="admin.avatar" :src="admin.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
            <label v-if="admin.avatar" class="el-upload-list__item-status-label avatar-uploader__status_label" @click.stop="handleRemove()"><i class="el-icon-delete"></i></label>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('Address')" prop="location">
          <el-select v-model="admin.locationCountry" @change="(value) => changeCountry(value)" :placeholder="$t('请选择')">
            <el-option
              v-for="country in countrys"
              :key="country.id"
              :label="country.nameCn || country.nameEn"
              :value="country.id">
            </el-option>
          </el-select>

          <el-select v-model="admin.locationProvince" @change="(value) => changeProvince(value)" :placeholder="$t('请选择')">
            <el-option
              v-for="province in provinces"
              :key="province.id"
              :label="province.nameCn || province.nameEn"
              :value="province.id">
            </el-option>
          </el-select>

          <el-select v-model="admin.locationCity" :placeholder="$t('请选择')">
            <el-option
              v-for="city in citys"
              :key="city.id"
              :label="city.nameCn || city.nameEn"
              :value="city.id">
            </el-option>
          </el-select>

          <p></p>
          <el-input v-model="admin.location"/>
        </el-form-item>
        <el-form-item :label="$t('邮编')" prop="postalCode">
          <el-input v-model="admin.postalCode" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
        </el-form-item>
        <el-form-item :label="$t('Contact_number')" prop="mobile">
          <el-input v-model="admin.mobile" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
        </el-form-item>
        <el-form-item :label="$t('邮箱')" prop="email">
          <el-input v-model="admin.email" onkeyup="this.value=this.value.replace(/[ ]/g,'')"/>
        </el-form-item>
        <el-form-item :label="$t('Partner_role')" prop="roleIds">
          <el-col>
            <el-select  v-model="admin.roleIds" multiple collapse-tags :placeholder="$t('请选择')">
              <el-option v-for="item in roles" :value="item.value" :label="item.label"/>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item :label="$t('Store_belong')" prop="shopId">
          <el-select v-model="admin.shopId" :clearable="!shop" :placeholder="$t('请选择')" >
            <el-option v-for="item in shops" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="updatePasswordVisible = true">{{$t('重置密码')}}</el-button>
        </el-form-item>
        <el-form-item :label="$t('New_password')" prop="password" v-show="updatePasswordVisible">
          <el-input v-model="admin.password" show-password/>
        </el-form-item>
        <el-form-item :label="$t('Confirm_password')" prop="validatePassword" v-show="updatePasswordVisible">
          <el-input v-model="validatePassword" show-password/>
        </el-form-item>-

<!--        <el-form-item :label="$t('Account_login')" prop="username">
          <el-col :span="6">
            <el-input v-model="admin.username" :disabled="true"/>
          </el-col>
          <el-col :span="6" align="center">
            <el-button @click="updatePasswordVisible = true">修改密码</el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="登录密码" prop="password" v-show="updatePasswordVisible">
          <el-input v-model="admin.password" show-password/>
        </el-form-item>
        <el-form-item :label="$t('Confirm_password')" prop="validatePassword" v-show="updatePasswordVisible">
          <el-input v-model="validatePassword" show-password/>
        </el-form-item>-->
       <el-form-item :label="$t('备注信息')">
          <el-input v-model="admin.remark" type="textarea"/>
        </el-form-item>
      </el-form>
      <div class="op-container" align="center">
        <el-button icon="el-icon-error" type="info" plain1 @click="handleCancel">{{$t('Cancel')}}</el-button>
        <el-button icon="el-icon-success" type="warning" plain1  @click="handleEdit">{{$t('更新用户')}}</el-button>
      </div>
    </el-card>
  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
  .avatar-uploader__status_label{
    display: block;
    color: red;
  }
</style>

<script>
import { uploadPath } from '@/api/storage'
import { updateAdmin, readAdmin } from '@/api/admin'
import { roleOptions } from '@/api/role'
import { getToken } from '@/utils/auth'
import { getShopAll } from '@/api/shop'
import { listCountryRegion, listSubRegion } from '@/api/region'
import store from '@/store'

export default {
  name: 'sysAdminEdit',
  data() {
    const validateRegion = (rule, value, callback) => {
        if (this.admin.locationCountry
          && this.admin.locationProvince
          && this.admin.locationCity
          && this.admin.location) {
          callback()
        } else {
          callback(new Error('请选择完整的区域信息'))
        }
      }

    const validatePass = (rule, value, callback) => {
      if (this.updatePasswordVisible) {
        if (!value) {
          callback(new Error(this.$t('Password_cannot_be_empty')));
        } else if (value.length < 6 || value.length > 16) {
          callback(new Error(this.$t('Password_length_from_6_-_16_characters')));
        }
      }

      callback();
    };

    const validateRePass = (rule, value, callback) => {
      if (this.updatePasswordVisible) {
        if (!this.validatePassword) {
          callback(new Error(this.$t('Password_cannot_be_empty')));
        } else if (this.validatePassword.length < 6 || this.validatePassword.length > 16) {
          callback(new Error(this.$t('Password_length_from_6_-_16_characters')));
        } else if (this.validatePassword !== this.admin.password) {
          callback(new Error(this.$t('Please_re-enter_password')));
        }
      }

      callback();
    };

    return {
      // 当前店铺
      shop: store.state.user.shop,
      uploadPath,
      admin: {
        avatar:'',
        locationCountry: undefined,
        locationProvince: undefined,
        locationCity: undefined,
        location: undefined
      },
      roles: [],
      shops: [],
      countrys: [],
      provinces: [],
      citys: [],
      validatePassword: null,
      updatePasswordVisible: false,
      rules: {
        username: [
          { required: true, message: this.$t('Controller_name_cannot_be_empty'), trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        validatePassword: [
          { validator: validateRePass, trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('员工代号不能为空'), trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: this.$t('员工名称不能为空'), trigger: 'blur' }
        ],
        socialSecurityNumber: [
          { required: true, message: this.$t('社保号码不能为空'), trigger: 'blur' }
        ],
        gender: [
          { required: true, message: this.$t('性别不能为空'), trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: this.$t('生日不能为空'), trigger: 'blur' }
        ],
        location: [
          { required: true, validator: validateRegion, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: this.$t('联系电话不能为空'), trigger: 'blur' }
        ],
        email: [
          { required: true, message: this.$t('邮箱不能为空'), trigger: 'blur' }
        ],
        postalCode: [
          { required: true, message: this.$t('邮编不能为空'), trigger: 'blur' }
        ]
    }
    }
  },
  created() {
    this.initData()
    const shopId = this.$route.query.shopId || null
    roleOptions(shopId).then(res => {
      this.roles = res.data.data.list
    })
    getShopAll().then(res=>{
      this.shops = res.data.data;
    })
    // 加载国家
    listCountryRegion().then(response=>{
      this.countrys = response.data.data.list
    })
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  methods: {
    test(val){
    },
    initData() {
      const id = this.$route.query.id
      if (!id) {
        return
      }
      readAdmin(id).then((res) => {
        this.admin = res.data.data
        this.admin.password = undefined;
        let countryId = this.admin.locationCountry
        if (countryId) {
          let query = {
            id: countryId,
            type: 2
          }
          listSubRegion(query).then(response=>{
            this.provinces = response.data.data.list
          })
        }

        let provinceId = this.admin.locationProvince
        if (provinceId) {
          let query = {
            id: provinceId,
            type: 2
          }
          listSubRegion(query).then(response=>{
            this.citys = response.data.data.list
          })
        }

      })
    },
    handleEdit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateAdmin(this.admin)
            .then(() => {
              this.$notify.success({
                title: this.$t('Success!'),
                message: '更新管理员成功'
              })

              // this.$router.push({ path: '/shop/admin'})

              // 删除当前标签页，跳转至上一个页面
              this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
              this.$router.go(-1)
            })
            .catch(response => {
              this.$notify.error({
                title: this.$t('Failed'),
                message: this.$t(response.data.errmsg)
              })
            })
        }
      })
    },
    changeCountry (value) {
      this.provinces = []
      this.citys = []
      this.admin.locationProvince = undefined
      this.admin.locationCity = undefined

      let query = {
        id: value,
        type: 2
      }
      listSubRegion(query).then(response=>{
        this.provinces = response.data.data.list
      })
    },
    changeProvince (value) {
      this.citys = []
      this.admin.locationCity = undefined

      let query = {
        id: value,
        type: 2
      }
      listSubRegion(query).then(response=>{
        this.citys = response.data.data.list
      })
    },
    uploadAvatar: function(response) {
      this.admin.avatar = response.data.url
    },
    handleCancel(){
      // this.$router.push({ path: '/shop/admin'})

      // 删除当前标签页，跳转至上一个页面
      this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
      this.$router.go(-1)
    },
    handleRemove(){
      this.admin.avatar = undefined
    }
  }
}
</script>

<style scoped>

</style>
